<template>
  <slot></slot>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

import { useRouter } from 'vue-router'
import { GoogleLogin } from '@/api/GoogleLogin/index'

const error = ref(null)
const router = useRouter()

const handleCredentialResponse = async (response) => {
  try {
    const token = response.credential
    const res = await GoogleLogin({ token })
    if (res.data.success) {
      localStorage.setItem('user', JSON.stringify(res.data.info.name))
      localStorage.setItem('smart_admin_user_token', res.data.result)
      localStorage.setItem('avatar', res.data.info.picture)
      await router.push('/home')
    } else {
      error.value = '登录失败，请重试'
    }
  } catch (err) {
    error.value = '登录失败，请重试'
    console.error('登录错误:', err)
  }
}

const initializeGoogleSignIn = () => {
  window.googleCallback = handleCredentialResponse
  const script = document.createElement('script')
  script.src = 'https://accounts.google.com/gsi/client'
  script.async = true
  script.defer = true
  document.head.appendChild(script)
}

onMounted(() => {
  initializeGoogleSignIn()
})

onUnmounted(() => {
  const script = document.querySelector(
    'script[src="https://accounts.google.com/gsi/client"]',
  )
  if (script) {
    document.head.removeChild(script)
  }
})
</script>

<style scoped></style>
